/*
 * VentanaNuevoAlimento.java
 *
 * Created on 18 de septiembre de 2008, 07:41
 */

package vista;

//import controlador.ControladorAlta;
//import controlador.ControladorConsulta;
//import datos.ElementoSql;
//import datos.Modificacion;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import dominio.Elemento;
import vista.util.VentanaNuevoAlimentoUtil;

/**
 *
 * @author  marcelo
 */
public class VentanaNuevoAlimento extends javax.swing.JFrame 
{
    private Collection alimentos = new ArrayList();
    private boolean seleccionado;
    private VentanaNuevoAlimentoUtil util = new VentanaNuevoAlimentoUtil();

    /** Creates new form VentanaNuevoAlimento */
    public VentanaNuevoAlimento() {
        initComponents();
        this.inicializar();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTableAlimentos = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jTextFieldTipo = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldNombre = new javax.swing.JTextField();
        jButtonGuardar = new javax.swing.JButton();
        jButtonModificar = new javax.swing.JButton();
        jButtonSalir = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Nuevo Alimento");
        setResizable(false);

        jTableAlimentos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "Codigo", "Tipo", "Nombre"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTableAlimentos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTableAlimentosMouseClicked(evt);
            }
        });
        jTableAlimentos.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTableAlimentosKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(jTableAlimentos);

        jLabel1.setBackground(new java.awt.Color(255, 255, 204));
        jLabel1.setText("Tipo");
        jLabel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jLabel1.setOpaque(true);

        jLabel2.setBackground(new java.awt.Color(255, 255, 204));
        jLabel2.setText("Nombre");
        jLabel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jLabel2.setOpaque(true);

        jButtonGuardar.setText("Guardar");
        jButtonGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonGuardarActionPerformed(evt);
            }
        });

        jButtonModificar.setText("Modificar");
        jButtonModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonModificarActionPerformed(evt);
            }
        });

        jButtonSalir.setText("Salir");
        jButtonSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSalirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 583, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jTextFieldTipo, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jTextFieldNombre, javax.swing.GroupLayout.DEFAULT_SIZE, 252, Short.MAX_VALUE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jButtonGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 80, Short.MAX_VALUE)
                                        .addComponent(jButtonModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(259, 259, 259))))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(420, 420, 420)
                        .addComponent(jButtonSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextFieldTipo, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextFieldNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonSalir)
                    .addComponent(jButtonGuardar)
                    .addComponent(jButtonModificar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButtonSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSalirActionPerformed
// TODO add your handling code here:
    this.dispose();
}//GEN-LAST:event_jButtonSalirActionPerformed

private void jButtonGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGuardarActionPerformed
// TODO add your handling code here:
    this.guardar();
}//GEN-LAST:event_jButtonGuardarActionPerformed

private void jTableAlimentosKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTableAlimentosKeyReleased
    if(evt.getKeyCode() == 127)
        this.eliminar();
}//GEN-LAST:event_jTableAlimentosKeyReleased

private void jTableAlimentosMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_jTableAlimentosMouseClicked
{//GEN-HEADEREND:event_jTableAlimentosMouseClicked
    // TODO add your handling code here:
    this.seleccionado = true;
    this.seleccionarFila();
}//GEN-LAST:event_jTableAlimentosMouseClicked

private void jButtonModificarActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButtonModificarActionPerformed
{//GEN-HEADEREND:event_jButtonModificarActionPerformed
    // TODO add your handling code here:
    this.modificar();
}//GEN-LAST:event_jButtonModificarActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VentanaNuevoAlimento().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonGuardar;
    private javax.swing.JButton jButtonModificar;
    private javax.swing.JButton jButtonSalir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableAlimentos;
    private javax.swing.JTextField jTextFieldNombre;
    private javax.swing.JTextField jTextFieldTipo;
    // End of variables declaration//GEN-END:variables

    ///////// INICIALIZACION DE FORMULARIO /////////////////////
    private void inicializar()
    {
        this.centrar();
        this.ajustarTamanioColumna();
        this.limpiar();
        this.cargarTabla();
    }
    
    private void centrar()
    {
        Dimension pantalla, cuadro;
	pantalla = Toolkit.getDefaultToolkit().getScreenSize();
	cuadro = this.getSize();
	this.setLocation(((pantalla.width - cuadro.width)/2), (pantalla.height - cuadro.height)/2);
    }
    
    private void ajustarTamanioColumna()
    {
        TableColumn column = null;
        for (int i = 0; i < 3; i++)
        {
            column = jTableAlimentos.getColumnModel().getColumn(i);
            switch(i)
            {
                case 0:
                        column.setPreferredWidth(15);
//                        System.out.println(column.getPreferredWidth());
                        break;
                case 1:
                        column.setPreferredWidth(108);
//                        System.out.println(column.getPreferredWidth());
                        break;
                case 2:
                        column.setPreferredWidth(247);
//                        System.out.println(column.getPreferredWidth());
                        break;
            }
        }
    }



    private void cargarTabla()
    {
        this.alimentos = this.util.traerTodos(this.jTableAlimentos, this.alimentos);
    }

    /**
     * Metodo para limpiar los registros de la tabla.
     * Quita todas las filas de la tabla.
     */
    private void limpiar()
    {
        DefaultTableModel modelo = (DefaultTableModel)this.jTableAlimentos.getModel();
        while(this.jTableAlimentos.getRowCount() != 0)
                modelo.removeRow(0);
        modelo = null;
    }


    ////////////// GUARDAR REGISTRO /////////////////////////////////

    private boolean verificaBlancos()
    {
     boolean bandera = true;
     String var;
     var= this.jTextFieldNombre.getText();
     if ( var.trim().length()== 0)
         bandera = false;
     var = this.jTextFieldTipo.getText();
     if ( var.trim().length()== 0)
         bandera = false;
     return bandera;
    }


    /**
     * este metodo se encarga de guardar el nuevo alimento ingresado por el usuario.
     * Basicamente comprende 2 procesos:
     * 1)_ Controlar que todos los campos solicitados esten cargados.
     * 2)_ Guardar el nuevo registro.
     */
    private void guardar()
    {
        if (this.verificaBlancos()) // verifica si todos los campos estan cargados
        {
            Elemento elemento = new Elemento();
            elemento.setTipo(this.jTextFieldTipo.getText().trim().toUpperCase());
            elemento.setNombre(this.jTextFieldNombre.getText().trim().toUpperCase());
            this.util.nuevoElemento(elemento);
            this.jTextFieldNombre.setText("");
            this.jTextFieldTipo.setText("");
            this.jTextFieldTipo.requestFocus();
            this.limpiar();
            this.cargarTabla();
        }
        else
            JOptionPane.showMessageDialog(null, "Asegurese de que los campos esten llenos","Hay campos en blancos",JOptionPane.ERROR_MESSAGE);
    }

    private void modificar()
    {
        if(this.verificaBlancos() && this.seleccionado)
        {
            this.util.modificarElemento(this.getElemento());
            this.jTextFieldNombre.setText("");
            this.jTextFieldTipo.setText("");
            this.jTextFieldTipo.requestFocus();
            this.limpiar();
            this.cargarTabla();
        }
        else
            JOptionPane.showMessageDialog(null, "Debe seleccionar un tema para modificar","No hay tema selecionado",JOptionPane.ERROR_MESSAGE);
    }

    ///////////////////////////////// mostrar datos seleccionados del grid

    private void seleccionarFila()
    {
        this.jTextFieldTipo.setText(String.valueOf(this.jTableAlimentos.getValueAt(this.jTableAlimentos.getSelectedRow(), 1)).toUpperCase());
        this.jTextFieldNombre.setText(String.valueOf(this.jTableAlimentos.getValueAt(this.jTableAlimentos.getSelectedRow(), 2)).toUpperCase());
    }

    private Elemento getElemento()
    {
        int codigo = Integer.parseInt(String.valueOf(this.jTableAlimentos.getValueAt(this.jTableAlimentos.getSelectedRow(), 0)));
        Elemento e = new Elemento();
        e.setCodigo(codigo);
        e.setTipo(this.jTextFieldTipo.getText().trim().toUpperCase());
        e.setNombre(this.jTextFieldNombre.getText().trim().toUpperCase());
        return e;
    }


    private void eliminar()
    {
        if(this.verificaBlancos())
        {
            this.util.eliminarElemento(this.getElemento());
            this.jTextFieldNombre.setText("");
            this.jTextFieldTipo.setText("");
            this.jTextFieldTipo.requestFocus();
            this.limpiar();
            this.cargarTabla();
        }
        else
            JOptionPane.showMessageDialog(null, "Debe seleccionar un alimento para modificar","No hay alimento selecionado",JOptionPane.ERROR_MESSAGE);
    }
    
}
